<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/16
 * Time: 13:50
 */

namespace Modules\Api\Service;

use HiCommon\Repository\UpKeepRepository;
use HiCommon\Repository\UpkeepTypeRepository;
use HiCommon\Repository\UsersVehicleRepository;

class UpKeepService extends BaseService
{


    /**
     *  保养记录列表
     *  hinq 2019 11 16
     *
     **/
    public function list_upkeep( array $arr_input ){
        try{
            //获取当前登录用户指定车辆的保养记录列表
            $user_id = api_user_id();
            $arr_option['where'] = ['user_id'=>$user_id ,'status'=>1 ,  'car_id' => $arr_input['car_id'] ];
            $arr_option['order'] = ['key'=>'id','value'=>'desc'];
            $arr_option['field'] = ['id','car_id','user_id','upkeep_time','upkeep_mileage','type','upkeep_types'];
            $arr_list = UpKeepRepository::get_all( (array) $arr_option )->toArray();   //没有分页 获取所有的保养记录
            $data['data'] = $arr_list;
            //保养项目名称列表
            $types = self::upkeep_types()['data'];
            $temp = array_column( $types , 'title', 'id');  //id为键title为值的数组
            $arr_temp = [];  //最后一次添加的保养记录 ， 通过这个数据计算下次保养信息
            //计算下次保养的详细信息
            foreach ( $data['data'] as $key=>&$item ){
                $ids = explode(',' , $item['upkeep_types']);
                $item['upkeep_types'] = [];
                if( count( $ids ) > 0 ){
                    foreach ( $ids as $vo ){
                        $item['upkeep_types'][] = $temp[$vo];
                    }
                }
                $item['upkeep_time'] = date('Y-m-d' , $item['upkeep_time'] );
                if( $key == 0 ){  //根据第一条数据计算下一次保养信息
                    $arr_temp = $item;
                }
            }
            //获取车辆信息
            $arr_option3['field'] = ['id','plate_no','brand_model'];
            $car_info = UsersVehicleRepository::get_one( (int) $arr_input['car_id'] , (array) $arr_option3 );
            $data['car_info'] = $car_info;
            $info = null;   //安卓端需求 没有数据的时候返回null
            if( $arr_temp ){
                //下次保养记录信息
                //在上次保养的时间上添加6个月时间
                $info['next_time'] = date("Y-m-d",strtotime("+6 months",strtotime( $arr_temp['upkeep_time'] ) ) );
                $info['next_mileage'] = $arr_temp['upkeep_mileage'] + 5000;   //在上次保养的数据上增加5000公里
                $info['next_day'] = ceil( ( strtotime( $info['next_time'] ) - time()) / 3600 / 24 );  //计算还有多少天倒计时  有可能（<=> 0 ）

                $info['next_msg'] = '正常保养';
                if( $info['next_day'] == 0 ){
                    $info['next_day'] = 0;
                }else if( $info['next_day'] < 1 ){
                    $info['next_msg'] = '保养时间已过，请添加最近一次的保养信息';
                }
            }
            $data['next_info'] = $info;
            return hello_success('ok',$data);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  验证提交数据的有效性
     *  hinq 2019 11 16
     *
     **/
    public function check_data( array $arr_input ){
        if( empty( $arr_input['car_id'] ) ){
            return hello_error('请选择车辆');
        }
        if( empty( $arr_input['upkeep_time'] ) ){
            return hello_error('保养时间不能为空');
        }
        if( empty( $arr_input['upkeep_mileage'] ) ){
            return hello_error('保养里程不能为空');
        }
        if( empty( $arr_input['upkeep_types'] ) ){
            return hello_error('保养项目不能为空');
        }
        return $arr_input;
    }


    /**
     *  手动添加保养记录   改版后已经没有系统添加的保养记录2020 3 1
     *  hinq 2019 11 16
     *  2020611: 添加保养信息时 判断之前是否有保养信息  不管之前的保养记录是啥都修改为不可推送状态
     *           保养推送 和 app用户端的信息都按照用户最后一条保养记录为准  mm
     *     推送消息根据当前车辆的最后一条保养记录推送
     **/
    public function store_upkeep( array $arr_input ){
        try{
            $temp = self::check_data( (array) $arr_input );
            if( $temp['state'] == 1 ){
                return $temp;
            }
            $user_id = api_user_id();
            $data['car_id'] = $temp['car_id'];          //汽车id
            $data['user_id'] = $user_id;            //用户id
            $data['upkeep_time'] = strtotime( $temp['upkeep_time'] );       //保养时间
            $data['upkeep_mileage'] = $temp['upkeep_mileage'];      //保养公里数
            $data['upkeep_types'] = $temp['upkeep_types'];      //保养的项目 多个用逗号隔开
            $data['type'] = 2;          //  类型： 1：系统添加保养（已删除）   2：手动添加保养
            $data['status'] = 1;
            $data['is_push'] = 0;

            //获取当前用户之前是否添加了保养记录数据
            $where['user_id'] = $user_id;
            UpKeepRepository::edit_where( $where , ['is_push'=>5]);   //将当前用户之前的数据都修改为不需要推送状态
            $res = UpKeepRepository::add_one( (array) $data );
            if( empty( $res ) ){
                return hello_error('添加失败');
            }
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }

    /**
     *  获取指定记录详情
     *  hinq 2019 11 18
     *
     **/
    public function detail_upkeep( int $nId ){
        try{
            if( empty( $nId ) ){
                return hello_error('参数错误');
            }
            $user_id = api_user_id();
            $arr_option['where'] = ['user_id'=>$user_id];
            $arr_option['field'] = ['id','upkeep_time','upkeep_mileage','upkeep_types'];
            //获取指定保养记录详情
            $arr_list = UpKeepRepository::get_one((int) $nId , (array) $arr_option );
            if( empty( $arr_list->first() ) ){
                return hello_error('参数错误');
            }
            $arr_list = $arr_list->toArray();
            $arr_list['upkeep_time'] = date('Y-m-d',$arr_list['upkeep_time']);
            $arr_list['upkeep_types'] = explode(',',$arr_list['upkeep_types']);
            //获取所有的保养项目类型列表
            $arr_types = self::upkeep_types()['data'];
            foreach ( $arr_types as $key => &$item ){
                $item['checked'] = false;
                if( in_array( $item['id'] , $arr_list['upkeep_types'] ) ){   //保养类型是否选中
                    $item['checked'] = true;
                }
            }
            unset( $arr_list['upkeep_types'] );
            $arr_list['upkeep_types'] = $arr_types;
            return hello_success('ok',$arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  编辑指定的保养数据
     *  hinq 2019 11 18
     *
     **/
    public function update_upkeep( array $arr_input ){
        try{
            $temp = self::check_data( (array) $arr_input );  //验证数据有效性
            if( $temp['state'] == 1 ){
                return $temp;
            }
            $data['car_id'] = $arr_input['car_id'];     //汽车id
            $data['upkeep_time'] = strtotime( $arr_input['upkeep_time'] );      //保养时间
            $data['upkeep_mileage'] = $arr_input['upkeep_mileage'];         //保养公里数
            $data['upkeep_types'] = $arr_input['upkeep_types'];         //保养类型 多个用逗号隔开
            $data['id'] = $arr_input['id'];
            $res = UpKeepRepository::edit_one( (array) $data );
            if( empty( $res ) ){
                return hello_error('编辑失败');
            }
            return hello_success('ok');
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }


    /**
     *  获取所有的保养项目列表
     *  hinq 2019 11 18
     *
     **/
    public function upkeep_types(){
        try{
            //获取所有的保养项目类型列表
            $arr_option['where'] = ['status'=>1];
            $arr_option['order'] = ['key'=>'sort','value'=>'asc'];
            $arr_option['field'] = ['id','title','remark'];
            $arr_list = UpkeepTypeRepository::get_all( (array) $arr_option )->toArray();
            return hello_success('ok',$arr_list);
        }catch ( \Exception $exception ){
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
    }
}

